package org.wu.framework.lazy.orm.database.jpa.repository.support.method;

import org.wu.framework.core.CamelAndUnderLineConverter;
import org.wu.framework.core.NormalUsedString;
import org.wu.framework.lazy.orm.database.jpa.repository.enums.MethodName2SQLType;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class LazyDeleteMethodSupport extends AbstractLazyDynamicMethodSimpleQuerySupport {
    /**
     * 支持的方法转换类型
     *
     * @return MethodName2SQLType 集合
     */
    @Override
    protected List<MethodName2SQLType> supportMethodName2SQLTypeList() {
        return List.of(MethodName2SQLType.DELETE, MethodName2SQLType.REMOVE);
    }

    /**
     * 方法名称转换成sql
     *
     * @param method 方法
     * @return sql
     */
    @Override
    public String methodName2SQL(Method method) {
        // deleteByIdAndName
        String mainTableName = getMainTableName(method);
        String methodName = method.getName();

        // deleteByIdAndName --> delete_by_id_and_name
        String methodNameToLine = CamelAndUnderLineConverter.humpToLine2(methodName);

        // byString[0]=delete byString[1]=id_and_name
        String[] byString = methodName.split(methodKeyBy);

        String format = String.format("delete from %s", mainTableName);
        if (byString.length > 0) {

            format += NormalUsedString.SPACE + NormalUsedString.WHERE + NormalUsedString.SPACE;
            // id_and_name
            String condition = byString[1];
            String[] columnList = condition.split(methodKeyAnd);

            String andList = Arrays.stream(columnList)
                    .map(whereColumn ->
                            whereColumn +
                                    NormalUsedString.SPACE + NormalUsedString.EQUALS +
                                    NormalUsedString.SPACE + NormalUsedString.LEFT_BRACE +
                                    whereColumn +
                                    NormalUsedString.SPACE + NormalUsedString.RIGHT_BRACE)
                    .collect(Collectors.joining(NormalUsedString.SPACE + NormalUsedString.AND + NormalUsedString.SPACE));
            return format + andList;
        } else {

            return format;
        }
    }
}
